package ch.fhnw.apsi.fortune;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedList;

/**
 * Reads one single File from Fortune and allows to get a random quote. Copyright is probably by BSD. The file was
 * installed using cygwin.
 * 
 * @author Claude Martin
 * 
 */
public enum Fortune {
  SINGLETON;
  private final LinkedList<String> quotes = new LinkedList<>();
  private boolean isOK = false;

  private static final String SOURCE = "computers";

  private Fortune() {
    try {
      try (InputStream resourceAsStream = Fortune.class.getResourceAsStream(SOURCE)) {
        try (final BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream))) {
          final StringBuilder sb = new StringBuilder();
          String line;
          while ((line = reader.readLine()) != null)
            if ("%".equals(line)) {
              this.quotes.add(sb.toString());
              sb.setLength(0);
            } else
              sb.append(line + "\n");
          this.quotes.add(sb.toString());
        }
      }
      Collections.shuffle(this.quotes);
      this.isOK = true;
    } catch (final Exception e) {
      this.isOK = false;
    }
  }

  public synchronized String getRandomQuote() {
    if (!this.isOK)
      return "Zugriff auf Zitatliste fehlgeschlagen.";
    final String first = this.quotes.removeFirst();
    this.quotes.addLast(first);
    return first;
  }
}
